#!/usr/bin/env bash
# taken from https://gist.github.com/jterrace/2911875

XVFB=/usr/bin/Xvfb
XVFBARGS=":1 -screen 0 1024x768x24 -ac +extension GLX +render -noreset"

if [ -z "$XDG_RUNTIME_DIR" ];
then
    export XDG_RUNTIME_DIR=/run/user/$(id -u)
fi

if ! touch $XDG_RUNTIME_DIR/.can_i_write 2>/dev/null;
then
    export XDG_RUNTIME_DIR=~/.run/user/$(id -u)
    mkdir -p $XDG_RUNTIME_DIR
    chmod 700 $XDG_RUNTIME_DIR
fi

PIDFILE=$XDG_RUNTIME_DIR/xvfb.pid

case "$1" in
  start)
    echo -n "Starting virtual X frame buffer: Xvfb"
    start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS
    echo "."
    ;;
  stop)
    echo -n "Stopping virtual X frame buffer: Xvfb"
    start-stop-daemon --stop --quiet --pidfile $PIDFILE
    echo "."
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage: /etc/init.d/xvfb {start|stop|restart}"
    exit 1
esac

exit 0
